/**
* All Rights Reserved , Copyright (C) 2021 , 青岛鼎信通讯股份有限公司
*
* MmsDeptExtraInfoService
* 部门扩展信息表新
*
* 修改纪录
* 2021-06-16 版本：1.0 hudeyong 创建。
* @version 版本：1.0
* @author 作者：hudeyong
* 创建日期：2021-06-16
*/
package com.topscomm.mms.service.impl;

import java.util.*;
import java.util.stream.Collectors;

import cn.hutool.core.util.ObjectUtil;
import com.topscomm.basic.BasicEntity;
import com.topscomm.basic.exception.ServiceException;
import com.topscomm.basic.util.SQLAdapter;
import com.topscomm.cbo.pojo.CboDeptEntity;
import com.topscomm.cbo.pojo.CboUserEntity;
import com.topscomm.cbo.service.impl.CboDeptService;
import com.topscomm.cbo.service.impl.CboUserService;
import com.topscomm.mms.pojo.MmsDeptExtraInfoEntity;
import com.topscomm.pub.util.StringUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import com.topscomm.mms.service.IMmsDeptExtraInfoService;
import com.topscomm.mms.service.impl.auto.MmsDeptExtraInfoServiceAuto;
import com.topscomm.pub.util.ConvertUtil;
import com.topscomm.pub.util.StringBufferProxy;

@Service(value = "mmsDeptExtraInfoService")
@Scope(value = "singleton")
public class MmsDeptExtraInfoService extends MmsDeptExtraInfoServiceAuto implements IMmsDeptExtraInfoService {
	@Autowired
	private CboDeptService cboDeptService;
	@Autowired
	private CboUserService cboUserService;

	/**
	 *
	 * @description:获取本人作为财经副总可以勘误的单据
	 * @param usercode
	 * @return
	 * @author: jiangtao1
	 * @date: 2021年7月26日上午8:46:28
	 * @modify:
	 */
	@Override
	public String getCfoDeptCodes(String usercode) {
		List<String> fieldList = new ArrayList<String>();
		fieldList.add(" distinct deptcommoncode as deptcommoncode");
		StringBufferProxy sql = new StringBufferProxy();
		sql.appendSingle(" cfocode ='{0}' ", usercode);
		List<Map<String, Object>> resultMaps = this.queryMapFieldsByWhere(sql.toString(), fieldList);
		StringBuffer sBuffer = new StringBuffer();
		for (Map<String, Object> temp : resultMaps) {
			sBuffer.append(ConvertUtil.convertToString(temp.get("deptcommoncode"))).append(",");
		}
		String result;
		if (sBuffer.length() > 0) {
			result = "," + sBuffer.toString();
		} else {
			result = "";
		}
		return result;
	}

	/**
	 * @description: 根据编码截取一级部门编码
	 * @param deptCode
	 * @return java.lang.String
	 * @author: wangxinhua
	 * @date: 2021/7/7 14:47
	 * @modify:
	 */
	public String getSubStringFirstDeptCode(String deptCode) {
		if(deptCode.contains("_")) {
			List<String> codeSplit = Arrays.asList(deptCode.split("_"));
			if(codeSplit.get(1).length() > 4){
				codeSplit.set(1, codeSplit.get(1).substring(0,4));
				return StringUtils.join(codeSplit, "_");
			} else {
				return deptCode;
			}
		}else {
			if(deptCode.length()>4) {
				return deptCode.substring(0, 4);
			}else {
				return deptCode;
			}
		}
	}

	/**
	 * @description:获取省份信息编码
	 * @param deptCode
	 * @return
	 * @author: jiangtao1
	 * @date: 2021年3月9日下午4:42:48
	 * @modify:
	 */
	public String getDeptCommonCode(String deptCode) {
		String firstdeptcode = this.getSubStringFirstDeptCode(deptCode);
		StringBufferProxy sql = new StringBufferProxy();
		sql.appendLineSingle(" concat(',',concat("+ MmsDeptExtraInfoEntity.FieldDeptcode+",',')) like '%,{0},%' ", firstdeptcode);
		MmsDeptExtraInfoEntity mmsDeptExtraInfoEntity = this.queryObjectByWhere(sql.toString());
		String deptCommonCode = null;
		if (mmsDeptExtraInfoEntity != null) {
			deptCommonCode = mmsDeptExtraInfoEntity.getDeptcommoncode();
		}
		return deptCommonCode;
	}
	/**
	  * @description:  获取省总权限范围deptcommoncode
	  * @author xinfushuo
	  * @param usercode
	  * @return	所有作为省总的部门deptcommon 一般只有一个
	  * @date 2022/7/18
	  * @modify
	  */
	@Override
	public List<String> getAsPMDeptCommonCodeByUserCode(String usercode){
		StringBufferProxy sql = new StringBufferProxy();
		sql.appendSingle("{0} = '{1}'",MmsDeptExtraInfoEntity.FieldProvincemanagercode,usercode);
		return this.queryByWhere(sql.toString()).stream().map(e->e.getDeptcommoncode()).collect(Collectors.toList());
	}
	/**
	 * @description: 根据userCode获取他管辖范围（是该地区的省总或者财总）的deptCommonCode
	 * @author: duzehou
	 * @date: 2022/8/29 9:35
	 * @param: [userCode]
	 * @return: java.util.List<java.lang.String>
	 **/
	public List<String> getDeptCommonCodes(String userCode){
		StringBufferProxy sql = new StringBufferProxy();
		//sql语句拼接
		sql.appendSingle(" {0} = '{1}'",MmsDeptExtraInfoEntity.FieldProvincemanagercode,userCode);
		sql.appendSingle(" OR {0} = '{1}'",MmsDeptExtraInfoEntity.FieldCfocode,userCode);
		//SQl =  SELECT * FROM MMSDEPTEXTRAINFO WHERE PROVINCEMANAGERCODE = '0118' OR CFOCODE = '0118'
		List<MmsDeptExtraInfoEntity> mmsDeptExtraInfoEntities = this.queryByWhere(ConvertUtil.convertToString(sql));
		//如果没有管辖范围
		if (ObjectUtil.isEmpty(mmsDeptExtraInfoEntities)){
			return new ArrayList<>();
		}
		//如果有管辖范围
		return mmsDeptExtraInfoEntities.stream().map(MmsDeptExtraInfoEntity::getDeptcommoncode).collect(Collectors.toList());
	}

    @Override
	protected void updateAfter(Map<String, Object> map) throws ServiceException {
		super.updateAfter(map);
		this.sendMessageToFds(map,MmsDeptExtraInfoEntity.tableName);
		this.addValueToRedis(MmsDeptExtraInfoEntity.tableName);
	}

	@Override
	protected void afterInsert(BasicEntity entity) throws ServiceException {
		super.afterInsert(entity);
		Map<String, Object> map = entity.convertToMap();
		this.sendMessageToFds(map,MmsDeptExtraInfoEntity.tableName);
		this.addValueToRedis(MmsDeptExtraInfoEntity.tableName);
	}

	@Override
	protected void deleteAfter(String whereSql) {
		super.deleteAfter(whereSql);
		this.addValueToRedis(MmsDeptExtraInfoEntity.tableName);
	}
	
	/**
	 * @description: 根据用户工号用户的一级部门信息
	 * @param deptCode
	 * @return java.lang.String
	 * @author: wangxinhua
	 * @date: 2021/7/7 14:47
	 * @modify:
	 */
	public Map<String, Object> getDeptInfoByUsercode(String usercode) {
		StringBufferProxy sql = new StringBufferProxy();
		sql.appendSingle("code = ("
				+ " SELECT "
					+ " CASE WHEN instr(CODE , '_')>0 THEN substr(CODE, 1, instr( CODE, '_' ) + 4) ELSE substr(CODE, 1, 4) END AS firstdeptcode"
				+ " FROM CBODEPT "
				+ " WHERE"
				+ " id = ( SELECT deptid FROM CBOUSER WHERE code = '{0}')"
				+ ")",usercode);
		List<String> filedList = new ArrayList<String>();
		filedList.add(CboDeptEntity.FieldCode);
		filedList.add(CboDeptEntity.FieldName);
		List<Map<String, Object>> deptInfoList = cboDeptService.queryMapFieldsByWhere(sql.toString(), filedList);
		if(deptInfoList.size()>0) {
			return deptInfoList.get(0);
		}
		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("name", "");
		resultMap.put("code", "");
		return resultMap;
	}

}
